<template>
  <div>
    <#-- 搜索区域 -->
    <div class="search-area" style="margin-bottom: 20px">
      <#list table.fields as field>
        <#if field.propertyType == "String" && field.name != "description" && field.name != "image" && !(field.comment?? && field.comment?contains("富文本")) && !(field.comment?? && field.comment?contains("文件上传"))>
      <el-input v-model="search.${field.propertyName}" placeholder="${field.comment!'请输入${field.propertyName}'}" style="width: 200px; margin-right: 20px" />
        </#if>
      </#list>
      <el-button @click="searchMethod">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <#-- 表格 -->
    <el-table :data="tableData">
      <#list table.fields as field>
      <el-table-column prop="${field.propertyName}" label="${field.comment!'${field.propertyName}'}">
        <#if field.propertyType == "String" && (field.name == "description" || (field.comment?? && field.comment?contains("富文本")))>
        <template #default="{ row }">
          <div v-html="row.${field.propertyName}" style="height: 100px;overflow: auto"></div>
        </template>
        <#elseif field.name == "image" || (field.comment?? && field.comment?contains("文件上传"))>
        <template #default="{ row }">
          <el-image style="width: 100px; height: 100px" v-if="row.${field.propertyName}" :src="row.${field.propertyName}" fit="fill" />
        </template>
        </#if>
      </el-table-column>
      </#list>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="openDialog(row)" size="small">编辑</el-button>
          <el-dialog title="编辑${table.comment!'记录'}" v-model="dialogVisible" :append-to-body="true">
            <el-form :model="dialogForm" :rules="rules" ref="dialogFormRef">
              <#list table.fields as field>
                <#if !field.keyFlag>
              <el-form-item label="${field.comment!'${field.propertyName}'}" prop="${field.propertyName}">
                <#if field.propertyType == "String" && (field.name == "description" || (field.comment?? && field.comment?contains("富文本")))>
                <MyEditor :content="dialogForm.${field.propertyName}" @update="updateFullText" />
                <#elseif field.name == "image" || (field.comment?? && field.comment?contains("文件上传"))>
                <el-upload
                  class="uploader"
                  drag
                  :action="uploadPath"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccessAdd"
                  :on-error="handleAvatarErrorAdd"
                  :headers="{ Authorization: getStorage('TOKEN') }"
                >
                  <el-image style="width: 100px; height: 100px" v-if="dialogForm.${field.propertyName}" :src="dialogForm.${field.propertyName}" fit="fill" />
                  <el-icon v-else class="el-icon--upload"><UploadFilled /></el-icon>
                </el-upload>
                <#else>
                <el-input v-model="dialogForm.${field.propertyName}" placeholder="请输入${field.comment!'${field.propertyName}'}" />
                </#if>
              </el-form-item>
                </#if>
              </#list>
              <el-form-item>
                <el-button type="primary" @click="handleEdit">保存</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
          <el-popconfirm
            title="确定要删除吗？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="handleDelete(row)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <#-- 分页 -->
    <el-pagination
      layout="sizes, prev, pager, next, jumper, total"
      @size-change="findSize"
      @current-change="findPage"
      :page-size="pageSize"
      :current-page="currentPage"
      :total="total"
      :page-sizes="[5, 10, 20, 30, 50]"
      style="text-align: center; padding-top: 20px" />

    <#-- 添加表单 -->
    <el-button @click="toggleAddUserForm" type="success" style="margin-top: 30px">添加${table.comment!'记录'}</el-button>
    <div v-show="showAddForm" class="transition-box" style="margin-top: 20px;">
      <el-form :model="form" :rules="rules" ref="formRef">
        <#list table.fields as field>
          <#if !field.keyFlag>
        <el-form-item label="${field.comment!'${field.propertyName}'}" prop="${field.propertyName}">
          <#if field.propertyType == "String" && (field.name == "description" || (field.comment?? && field.comment?contains("富文本")))>
          <MyEditor :content="form.${field.propertyName}" @update="updateFullText" />
          <#elseif field.name == "image" || (field.comment?? && field.comment?contains("文件上传"))>
          <el-upload
            class="uploader"
            drag
            :action="uploadPath"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccessAdd"
            :on-error="handleAvatarErrorAdd"
            :headers="{ Authorization: getStorage('TOKEN') }"
          >
            <el-image style="width: 100px; height: 100px" v-if="form.${field.propertyName}" :src="form.${field.propertyName}" fit="fill" />
            <el-icon v-else class="el-icon--upload"><UploadFilled /></el-icon>
          </el-upload>
          <#else>
          <el-input v-model="form.${field.propertyName}" placeholder="请输入${field.comment!'${field.propertyName}'}" />
          </#if>
        </el-form-item>
          </#if>
        </#list>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { add, del, getPage, update } from '@/api/${entity}.js'
import { ElMessage } from 'element-plus'
<#-- 检查是否需要导入 MyEditor 或 UploadFilled -->
<#assign hasRichText = false>
<#assign hasFileUpload = false>
<#list table.fields as field>
  <#if field.propertyType == "String" && (field.name == "description" || (field.comment?? && field.comment?contains("富文本")))>
    <#assign hasRichText = true>
  </#if>
  <#if field.name == "image" || (field.comment?? && field.comment?contains("文件上传"))>
    <#assign hasFileUpload = true>
  </#if>
</#list>
<#if hasRichText>
import MyEditor from '@/components/MyEditor.vue'
</#if>
<#if hasFileUpload>
import { UploadFilled } from '@element-plus/icons-vue'
</#if>

// 数据
const tableData = ref([])
const total = ref(0)
const pageSize = ref(5)
const currentPage = ref(1)

// 表单
let dialogForm = reactive({
  <#list table.fields as field>
  ${field.propertyName}: '',
  </#list>
})

const form = reactive({
  <#list table.fields as field>
  ${field.propertyName}: '',
  </#list>
})

const rules = {
  <#list table.fields as field>
    <#if !field.keyFlag>
  ${field.propertyName}: [{ required: true, message: '请输入${field.comment!'${field.propertyName}'}', trigger: 'blur' }],
    </#if>
  </#list>
}

const dialogVisible = ref(false)
const showAddForm = ref(false)
const dialogFormRef = ref(null)
const formRef = ref(null)
<#if hasFileUpload>
const uploadPath = 'http://localhost:8080/common/upload'
</#if>

// 分页方法
const findSize = (size) => {
  pageSize.value = size
  fetchData()
}

const findPage = (page) => {
  currentPage.value = page
  fetchData()
}

// 数据获取和操作方法
const fetchData = async (page = currentPage.value, size = pageSize.value, searchParams = search) => {
  const { data } = await getPage({ pageNum: page, pageSize: size, ...searchParams })
  tableData.value = data.records
  total.value = data.total
}

const openDialog = (row) => {
  dialogVisible.value = true
  Object.assign(dialogForm, row)
}

const handleEdit = async () => {
  dialogFormRef.value.validate().then(() => {
    update(dialogForm).then((res) => {
      if (res.code === 1) {
        ElMessage.success('更新成功')
        fetchData()
        dialogVisible.value = false
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}

const handleDelete = async (row) => {
  del(row.id).then((res) => {
    if (res.code === 1) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  })
}

const toggleAddUserForm = () => {
  showAddForm.value = !showAddForm.value
}

const onSubmit = async () => {
  formRef.value.validate().then(() => {
    add(form).then((res) => {
      if (res.code === 1) {
        ElMessage.success('添加成功')
        fetchData()
        resetForm()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

const resetForm = () => {
  Object.keys(form).forEach(key => {
    <#list table.fields as field>
      <#if !field.keyFlag>
    if (key === '${field.propertyName}') form[key] = ''
      </#if>
    </#list>
  })
}

// 搜索
const search = reactive({
  <#list table.fields as field>
    <#if field.propertyType == "String" && field.name != "description" && field.name != "image" && !(field.comment?? && field.comment?contains("富文本")) && !(field.comment?? && field.comment?contains("文件上传"))>
  ${field.propertyName}: null,
    </#if>
  </#list>
})

const searchMethod = () => {
  fetchData(currentPage.value, pageSize.value, search)
}

const resetSearch = () => {
  Object.keys(search).forEach(key => (search[key] = null))
  fetchData()
}

<#if hasRichText>
// 富文本处理
const updateFullText = (content) => {
  if (dialogVisible.value) {
    dialogForm.description = content
  } else {
    form.description = content
  }
}
</#if>

<#if hasFileUpload>
// 图片处理
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) ElMessage.error('上传文件只能是图片!')
  if (!isLt2M) ElMessage.error('上传图片大小不能超过 2MB!')
  return isImage && isLt2M
}

const handleAvatarSuccessAdd = (res, file) => {
  if (dialogVisible.value) {
    dialogForm.image = file.response.data
  } else {
    form.image = file.response.data
  }
}

const handleAvatarErrorAdd = (err) => {
  if (err.toString().includes('401')) {
    ElMessage.error('请先登录!')
    router.push('/login')
  } else {
    ElMessage.error(err.message || '上传失败')
  }
}
</#if>

onMounted(() => fetchData())
</script>

<style scoped lang="scss">
.transition-box {
  margin-bottom: 10px;
  width: 100%;
  border-radius: 4px;
  padding: 20px;
  box-sizing: border-box;
}
<#if hasFileUpload>
.uploader {
  width: 300px;
  border-radius: 6px;
  cursor: pointer;
}

.el-icon--upload {
  font-size: 67px;
  color: #8c939d;
  width: 100%;
  height: 100px;
  text-align: center;
}
</#if>
</style>
